from django.shortcuts import render
from django.http import JsonResponse
import datetime
import time
import json
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import TaskSerializer
from .serializers import FundTransactionRecordSerializer
from .serializers import StockTransactionRecordSerializer
from .serializers import FundRecordSerializer
from .models import Task
from .models import FundTransactionRecord
from .models import FundRecord
from .models import StockTransactionRecordBak
from django.db.models import F
from . import strategy
import requests
from . import WXBizDataCrypt
from django.conf import settings
import redis
import akshare as ak
from . import sma

@api_view(['GET'])
def apiOverview(request):
	api_urls = {
		'GetFundTransactionRecord': '/transactionrecord-list/<str:fid>/<str:lastdays>/<str:reserve>/',
		'CreateFundTransactionRecord': '/fundtransactionrecord-create/',
		'FundtransactionrecordDelete': '/fundtransactionrecord-delete/<str:pk>/',
		'FundtransactionrecordSync': '/fundtransactionrecord-sync/<str:pk>/',
		'StockTransactionRecordSync': '/stocktransactionrecord-sync/<str:pk>/',
		'FundRecordCreate': '/fundrecord-create/',
		'FundRecordList': '/fundrecords/<str:start_fid>/<str:end_fid>/',
		'SearchRecord': '/fundrecords-search/<str:s_id>/',
		'StockTransactionRecordList': '/stocktransactionrecord-list/<str:sid>/<str:reserve>/',
		'GetShCompany': '/get-sh-company',
		'GetSzCompany': '/get-sz-company',
		'StockTransactionRecordSma': '/stocktransactionrecord-sma/<str:sid>/'
		}
	return Response(api_urls)

@api_view(['GET'])
def taskList(request):
	tasks = Task.objects.all().order_by('-id')
	serializer = TaskSerializer(tasks, many=True)
	return Response(serializer.data)

@api_view(['GET'])
def fundRecordList(request, start_fid, end_fid):
	start_fid = start_fid.zfill(6)
	end_fid = end_fid.zfill(6)
	funds = FundRecord.objects.filter(fund_id__gte=start_fid, fund_id__lte=end_fid).order_by(F('fund_id').asc(nulls_last=True))
	serializer = FundRecordSerializer(funds, many=True)
	return Response(serializer.data)

@api_view(['GET'])
def searchRecord(request, s_id):
	funds = FundRecord.objects.filter(fund_id__startswith=s_id)
	serializer = FundRecordSerializer(funds, many=True)
	return Response(serializer.data[:20])

@api_view(['GET'])
def fundTransactionRecordList(request, fid, lastdays, reserve):
	records = {}
	end_ts = datetime.date.today()
	start_ts = end_ts - datetime.timedelta(days=int(lastdays))
	records = FundTransactionRecord.objects.filter(fund_id=fid,date__gte=start_ts,date__lte=end_ts).order_by(F('date').asc(nulls_last=True))
	serializer = FundTransactionRecordSerializer(records, many=True)
	data_ = strategy.buylowsellhigh(serializer.data)
	if(reserve=='1'):
		data_ = data_.iloc[::-1]
	return Response(data_.to_json(orient="table"))

@api_view(['GET'])
def stockTransactionRecordList(request, sid, items):
	records = StockTransactionRecordBak.objects.filter(stock_id=sid).order_by(F('day').desc(nulls_last=True))[:int(items)]
	serializer = StockTransactionRecordSerializer(records, many=True)
	data_ = strategy.stockbuylowsellhigh(serializer.data)
	return Response(data_.to_json(orient="table"))

@api_view(['POST'])
def authLogin(request):
	# print(request.data)
	red = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0)
	appId = "wx8d2eee9b3d25be68"
	encryptedData = request.data["encryptedData"]
	ivD = request.data["iv"]
	sessionKey = red.get('aifund-session-' + request.data["apiToken"])
	pc = WXBizDataCrypt.WXBizDataCrypt(appId, sessionKey)
	print(pc.decrypt(encryptedData, ivD))
	return Response('ok')

@api_view(['POST'])
def wxLogin(request):
	print(request.data)
	red = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=0)
	URL = "https://api.weixin.qq.com/sns/jscode2session"
	PARAMS = {
		"appid": settings.APPID,
		"secret": settings.SECRET,
		"js_code": request.data['code'],
		"grant_type": "authorization_code"
	}
	r = requests.post(url = URL, data = PARAMS)
	print(r.text)
	result = json.loads(r.text)
	token = WXBizDataCrypt.hash_string(result['session_key'])
	red.set('aifund-session-' + token, result['session_key'])
	return Response(token)

@api_view(['POST'])
def fundtransactionrecordCreate(request):
	serializer = FundTransactionRecordSerializer(data=request.data)
	if len(FundTransactionRecord.objects.filter(fund_id=request.data['fund_id'], date=request.data['date'])) > 0:
		return Response('{"status": "exists!"}')
	if serializer.is_valid():
		serializer.save()
	return Response(serializer.data)

@api_view(['POST'])
def fundrecordCreate(request):
	serializer = FundRecordSerializer(data=request.data)
	if serializer.is_valid():
		serializer.save()
	return Response(serializer.data)

@api_view(['DELETE'])
def fundtransactionrecordDelete(request, pk):
	task = FundTransactionRecord.objects.get(id=pk)
	task.delete()
	return Response('Item succsesfully delete!')

@api_view(['GET'])
def fundtransactionrecordSync(request, pk):
	end_ts = datetime.date.today()
	start_ts = end_ts - datetime.timedelta(days=90)
	fundData = strategy.get_fund_data(pk.zfill(6), '1', '90', start_ts, end_ts)
	for fund in fundData:
		fund['fund_id'] = pk
		serializer = FundTransactionRecordSerializer(data=fund)
		if len(FundTransactionRecord.objects.filter(fund_id=pk, date=fund['date'])) == 0:
			if serializer.is_valid():
				serializer.save()
	return Response('sync last 90 days data succsesfully!')

@api_view(['GET'])
def stockTransactionRecordSync(request, pk):
	dataset_ = strategy.get_stock_data(pk, 5, 5, 240)
	for data_ in dataset_:
		data_['stock_id'] = pk
		data_['open_price'] = data_['open']
		serializer = StockTransactionRecordSerializer(data=data_)
		if len(StockTransactionRecordBak.objects.filter(stock_id=pk, day=data_['day'])) == 0:
			if serializer.is_valid():
				serializer.save()
	return Response('sync last 1 days stock data succsesfully!')

@api_view(['GET'])
def getShCompany(request):
	stock_info_sh_df = ak.stock_info_sh_name_code(indicator="主板A股")
	return Response(stock_info_sh_df)

@api_view(['GET'])
def getSzCompany(request):
	stock_info_sz_df = ak.stock_info_sz_name_code(indicator="A股列表")
	data = {
		'COMPANY_CODE': [],
		'COMPANY_ABBR': []
	}
	code = []
	name = []
	code = stock_info_sz_df['A股代码']
	name = stock_info_sz_df['A股简称']
	data['COMPANY_CODE'] = code
	data['COMPANY_ABBR'] = name
	return Response(data)

@api_view(['GET'])
def getStockSmaValues(request, sid):
	records = StockTransactionRecordBak.objects.filter(stock_id=sid).order_by(F('day').desc(nulls_last=True))[:48]
	serializer = StockTransactionRecordSerializer(records, many=True)
	data_ = sma.cal_sma(serializer.data, 48)
	return Response(data_)
